package com.lz.helper.face

import android.os.Handler
import android.util.Log
import java.lang.ref.SoftReference

//先对比报名照, 再证件照, 并
class DoubleAndRequest (
    private val type: Int,
    private val photoParams: FeatureParams, //证件照
    private val examParams: FeatureParams, //报名照
    private val handler: Handler,
    callback: FeatureRequest.Callback?
) : FeatureRequest {

    companion object {
        const val TAG = "DoubleAndRequest"
    }

    private var reference = SoftReference(callback)

    override fun recognize(nvData: ByteArray, nvFeature: FloatArray, w: Int, h: Int): Int {
        //校验报名照
        val detect1 = examParams.detect()
        if (detect1 == null || detect1.size <= 1) {
            Log.d(TAG, "params1 callback detect err...")
            handler.post { reference.get()?.onFeatureError(type, ERR_DETECT) }
            return 1
        }
        val feature1 = examParams.feature()
        if (feature1 == null || feature1.isEmpty()) {
            Log.d(TAG, "params1 callback feature1 err...")
            handler.post { reference.get()?.onFeatureError(type, ERR_FEATURE) }
            return 2
        }

        //校验证件照
        val detect2 = photoParams.detect()
        if (detect2 == null || detect2.size <= 1) {
            Log.d(TAG, "params2 callback detect err...")
            handler.post { reference.get()?.onFeatureError(type, ERR_DETECT) }
            return 1
        }
        val feature2 = photoParams.feature()
        if (feature2 == null || feature2.isEmpty()) {
            Log.d(TAG, "params2 callback feature err...")
            handler.post { reference.get()?.onFeatureError(type, ERR_FEATURE) }
            return 2
        }

        val res1 = float2Double(distance(nvFeature, feature1))
        val res2 = float2Double(distance(nvFeature, feature2))
        Log.d(TAG, "callback feature res =  $res1, $res2")
        if (res1 >= examParams.threshold && res2 >= photoParams.threshold) { //成功
            val nvDataCopy = ByteArray(nvData.size)
            System.arraycopy(nvData, 0, nvDataCopy, 0, nvData.size)
            examParams.thresholdResult = res1
            handler.post {
                reference.get()?.onFeatureSuccess(type, nvDataCopy, w, h, photoParams, examParams)
            }
            return 0
        }
        return -1
    }

    override fun timeout() {
        Log.d(TAG, "------request timeout------")
        handler.post { reference.get()?.onFeatureError(type, ERR_TIMEOUT) }
    }
}